<?php


namespace App\logic;


use App\Models\users;
use App\servers\DxbSmsServer;
use App\servers\RedisService;
use App\servers\RlySmsServer;

class PhoneLogic
{
    /**
     * 静默登录
     * @name lzh
     * @param $code
     * @return mixed
     */
    public static function Logins($code){
        if (empty($code)) abort(500,'未携带登录login参数');
        $data=file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=wx8057de990a718879&secret=4cc8233d7593616525524163761d135d&js_code=$code&grant_type=authorization_code");
        $data=json_decode($data,true);
        $result=users::UserFind(['openid'=>$data['openid']]);
        if (empty($result))
        {
            $resd=[
                'openid'=>$data['openid'],
                'name'=>'游客用户'.rand(1000,9999),
                'icon'=>'http://ruwjymzbj.hn-bkt.clouddn.com/touxiang-kong.png',
                'created_at'=>date('Y-m-d H:i:s')
            ];
            $sql=users::UserInsert($resd);
            $result=users::UserFind(['openid'=>$data['openid']]);
        }
        return $result;
    }

    /**
     * 发送短信
     * @name lzh
     * @param $phone
     * @return int
     */
    public static function Phones($phone){
        if (empty($phone)) abort(500,'未携带发送短信的手机号参数');
        $code=rand(1000,9999);
        RedisService::getInstance()->getRedis()->select(4);
        RedisService::getInstance()->getRedis()->set('code'.$phone,$code);
        DxbSmsServer::sendCeshi($phone,$code);
//        (new RlySmsServer())->sendSms($phone);
        return $code;
    }

    /**
     * 绑定手机号
     * @name lzh
     * @param $phone
     * @param $code
     * @param $user_id
     * @return bool
     */
    public static function PhoneLogins($phone,$code,$user_id){
        if (empty($phone)) abort(500,'未携带发送短信的手机号参数');
        if (empty($code)) abort(500,'未携带验证码参数');
        if (empty($user_id)) abort(500,'未携带用户id参数');
        RedisService::getInstance()->getRedis()->select(4);
        $open=RedisService::getInstance()->getRedis()->get('code'.$phone);
        if ($open!=$code) {
            abort(500,'验证码错误');
        }else{
            users::UserPhone(['id'=>$user_id],['phone'=>$phone]);
        }
        return $open;
    }
}
